import logging
import simplejson
from axis4 import settings
from google.appengine.api import users
from django.http import Http404, HttpResponse
from django.shortcuts import redirect
import models

class BaseController(object):
    base_log = logging.getLogger(settings.MAIN_LOGGER)
    def __call__(self, request, url = "", **kwargs):
        self.base_log.info("\tRequesting " + url)

#        try:
        parts = url.rstrip("/").split('/')
        method = None
        try:
            method = parts[0]
        except:
            raise Http404
        if method is None:
            raise Http404
        if method == "":
            method = "index"
        if not hasattr(self, method):
            method = "default_function"
        self.base_log.debug("Final method " + method)
        if not hasattr(self, method):
            raise Http404
        method_func = getattr(self, method)
        return method_func(request, url, kwargs.get("user", None), *parts)
#        except Exception, e:
#            self.base_log.exception(e)
#            raise e

class JsonController(BaseController):
    def __call__(self, request, url="", **kwargs):
        try:
            return super(JsonController, self).__call__(request, url, **kwargs)
        except Exception, e:
            self.base_log.exception(e)
            return HttpResponse(simplejson.dumps({"success": False, "error": e.__unicode__()}))

class FormCallbackController(JsonController):
    def __call__(self, request, url="", **kwargs):
        resp = super(FormCallbackController, self).__call__(request, url, **kwargs)
        if request.GET.get("formcallback") is not None:
            callback_name = request.GET["formcallback"]
            resp.content = "<script type='text/javascript'>parent.window.%s(%s);</script>" % (callback_name, resp.content)
            resp['Content-Type'] = 'text/html; charset=utf-8'
        return resp

class JsonpCallbackController(FormCallbackController):
    def __call__(self, request, url="", **kwargs):
        resp = super(JsonpCallbackController, self).__call__(request, url, **kwargs)
        if request.GET.get("callback") is not None:
            callback_name = request.GET["callback"]
            resp.content = "%s(%s);" % (callback_name, resp.content)
            resp['Content-Type'] = 'text/javascript'
        return resp

class UnProtectedController(JsonpCallbackController):
    pass

class ProtectedController(JsonpCallbackController):
    def __call__(self, request, url="", **kwargs):
        user = users.get_current_user()
        if not user:
            return redirect(users.create_login_url(request.build_absolute_uri()))
        if not models.Account.all().filter("user =", user).count():
            models.Account(user = user).put()
        kwargs["user"] = user
        return super(ProtectedController, self).__call__(request, url, **kwargs)

class ProtectedPageController(BaseController):
    def __call__(self, request, url="", **kwargs):
        user = users.get_current_user()
        if not user:
            return redirect(users.create_login_url(request.build_absolute_uri()))
        if not models.Account.all().filter("user =", user).count():
            models.Account(user = user).put()
            kwargs["user"] = user
        return super(ProtectedPageController, self).__call__(request, url, **kwargs)

class ActualController(ProtectedController):
    def __call__(self, request, url="", **kwargs):
        return super(ActualController, self).__call__(request, url, **kwargs)
